﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebMvc.Controllers;
using Common;
using Models;
using System.Web;
using WebMvc.Areas.Models;
using ApiHelperBLL;
using ApiHelperBLL.Models;
using System.Threading.Tasks;
using WebMvc.Filters;
using System.Net.Http.Headers;
using System.IO;
using log4net;

namespace WebMvc.APIControllers
{
    [ApiSecurityFilter]
    public class AlibabaReportController : BaseApiController
    {
        ILog logWriter = LogManager.GetLogger("AlibabaAppointmentController");

        #region 报告查询接口
        /// <summary>
        /// 报告查询接口
        /// </summary>
        /// <param name="app_key">TOP分配给应用的Appkey</param>
        /// <param name="method">API接口名称</param>
        /// <param name="timestamp">时间戳，格式：yyyy-MM-dd HH:mm:ss</param>
        /// <param name="sign">请求签名，遵守TOP签名规范</param>
        /// <param name="cardId">卡号</param>
        /// <param name="orderId">订单号</param>
        /// <returns></returns>
        public Common.JsonData PostReport(string app_key, string method, string timestamp, string sign, string cardId, int orderId)
        {
            logWriter.Info("PostReport方法进入");
            if (string.IsNullOrEmpty(cardId) || orderId == 0)
            {
                return new Common.JsonData() { returnCode = "400", message = "输入参数异常", data = null };
            }
            try
            {
                var report = oc.BllSession.IBS_ReportBLL.Entities.Where(rep => rep.RCardId == cardId && rep.ROrderId == orderId).FirstOrDefault();
                if (report != null)
                {
                    //文件保存目录路径 
                    string SaveTempPath = "~/" + report.RUrl;
                    string dirTempPath = HttpContext.Current.Server.MapPath(SaveTempPath);

                    return new Common.JsonData() { returnCode = "200", message = "OK", data = FileUp.fileToBase64(dirTempPath) };//data = GContent(report.RUrl)
                }
                return new Common.JsonData() { returnCode = "400", message = "报告查询接口失败" };
            }
            catch (Exception ex)
            {
                logWriter.Error("PostReport" + ex.Message);
                return new Common.JsonData() { returnCode = "500", message = ex.Message, data = null };
            }
        }
        #endregion

        #region 转换PDF文件为MultipartFormDataContent
        public MultipartFormDataContent GContent(string pdfUrl)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/json"));//设定要响应的数据格式
                    using (var content = new MultipartFormDataContent())//表明是通过multipart/form-data的方式上传数据
                    {
                        //文件保存目录路径 
                        string SaveTempPath = "~/" + pdfUrl;
                        String dirTempPath = HttpContext.Current.Server.MapPath(SaveTempPath);

                        var files = this.GFileByteArrayContent(dirTempPath);//获取文件集合对应的ByteArrayContent集合
                        Action<List<ByteArrayContent>> act = (dataContents) =>
                        {//声明一个委托，该委托的作用就是将ByteArrayContent集合加入到MultipartFormDataContent中
                            foreach (var byteArrayContent in dataContents)
                            {
                                content.Add(byteArrayContent);
                            }
                        };
                        act(files);//执行act
                        return content;
                    }
                }
            }
            catch (Exception ex)
            {
                logWriter.Error("GContent" + ex.Message);
                throw ex;
            }
        }

        private List<ByteArrayContent> GFileByteArrayContent(string file)
        {
            List<ByteArrayContent> list = new List<ByteArrayContent>();

            var fileContent = new ByteArrayContent(File.ReadAllBytes(file));
            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = Path.GetFileName(file)
            };
            list.Add(fileContent);

            return list;
        }
        #endregion

       
    }
}
